import { Component, Fragment } from 'react';
import { TestChild } from "./testChild";
import './text.scss'

export class PageTest extends Component {
  constructor(props) {
    super(props)
    this.state = {
      msg: '',
      serviceName: '',
      serviceList: [{ text: '基础服务' }]
    }
  }

  vlidate(val) {
    return new Promise((resolve, reject) => {
      (val && val.length) ? resolve() : reject('值不能为空')
    })
  }

  async addService() {
    try {
      await this.vlidate(this.state.serviceName)
    } catch (error) {
      alert(error)
      return
    }

    const serviceList = this.state.serviceList
    const newList = serviceList.concat({ text: this.state.serviceName })
    this.setState({ serviceList: newList, serviceName: '' })
  }

  removeService(item) {
    const serviceList = this.state.serviceList
    const inx = serviceList.indexOf(item)
    if (inx > -1) {
      serviceList.splice(inx, 1)
      this.setState({ serviceList })
    }
  }

  updateServiceList() {
    const list = this.state.serviceList
    const listDom = list.map((item, i) => {
      return (<li key={i}>
        <TestChild content={item} removeFun={() => {this.removeService(item)}}></TestChild>
      </li>)
    })
    return <ol className="page list">{listDom}</ol>
  }

  updateServiceName(e) {
    this.setState({ serviceName: e.target.value })
  }

  render() {
    return (
      <Fragment>
        {/* react初体验 */}
        {/* <div dangerouslySetInnerHTML={{__html: this.state.serviceName}}></div> */}
        <input value={this.state.serviceName} onChange={(e) => this.updateServiceName(e)} />
        <button onClick={() => this.addService()}>添加增值服务</button>
        <div>{this.updateServiceList()}</div>
      </Fragment>
    )
  }
}